package ptumall.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import ptumall.model.Users;
import ptumall.service.UserService;
import ptumall.utils.JWTUtils;

import javax.crypto.SecretKey;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*") // 允许所有域名跨域访问
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private JWTUtils jwtUtil;

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, Object> request) {
        String code = (String) request.get("code");
        Map<String, Object> userInfo = (Map<String, Object>) request.get("userInfo");

        // 1. 调用微信接口获取 openid
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid
                + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        String response = new RestTemplate().getForObject(url, String.class);
        JSONObject json = JSON.parseObject(response);
        String openid = json.getString("openid");
        String sessionKey = json.getString("session_key"); // 用于敏感数据解密（可选）

        if (openid == null) {
            return ResponseEntity.badRequest().body("登录失败");
        }

        // 2. 查询或创建用户
        Users user = userService.findOrCreateUser(openid, userInfo);

        // 3. 生成 JWT Token
        String token = jwtUtil.generateToken(user);

        return ResponseEntity.ok(Collections.singletonMap("token", token));
    }
}


